// https://github.com/josdejong/jsoneditor/blob/master/docs/api.md
import JSONEditor from 'jsoneditor/dist/jsoneditor.min';
import 'jsoneditor/dist/jsoneditor.min.css';

export const modes = [
    'tree',
    'view',
    'form',
    'code',
    'text',
];

export default {
    props: {
        options: {
            type: Object,
            default() {
                return {};
            },
        },
        value: {
            default() {
                return {};
            },
        },
        autoExpand: Boolean,
    },
    data() {
        return {
            jsoneditor: null,
        };
    },
    watch: {
        value: {
            deep: true,
            handler(value) {
                this.jsoneditor.set(value);
                if (this.autoExpand) {
                    try {
                        this.jsoneditor.expandAll()
                    } catch (e) {
                    }
                }
            }
        },
    },
    methods: {
        getOptions() {
            const defaults = {
                escapeUnicode: false,
                history: true,
                indentation: 4,
                mode: modes[0],
                modes: modes.slice(0),
                navigationBar: true,
                search: true,
                statusBar: true,
                sortObjectKeys: false,
            };

            return Object.assign({}, defaults, this.options, {
                onChange: this.onChange,
                onError: this.onError,
            });
        },
        onChange() {
            this.newValue = this.jsoneditor.get()
        },
        onError(error) {
            this.$emit('error', error);
        },
        emitValue() {
            try {
                if (this.newValue) {
                    this.$emit('input', this.newValue);
                    this.newValue = ''
                }
            } catch (e) {
            }
        }
    },
    render(h) {
        return h('div', {
            ref: 'jsoneditor',
            on: {
                mouseleave: e => {
                    this.emitValue()
                }
            }
        });
    },
    mounted() {
        this.jsoneditor = new JSONEditor(
            this.$refs.jsoneditor,
            this.getOptions(),
            this.value,
        );
    },
    beforeDestroy() {
        this.jsoneditor.destroy();
        this.jsoneditor = null;
    },
};
